<script setup>
import { onBeforeMount, reactive, ref, toRefs, computed } from 'vue';
import { getNamespaceListHandler as getListHandler , createNamespaceHandler as createItem, deleteNamespaceHandler as deleteItem } from '../../api/namespace.js';
import { getClusterListHandler } from '../../api/cluster.js';
import {useRoute} from 'vue-router';
import Edit from './Edit.vue';
import Detail from './Detail.vue';
import { ElMessage } from 'element-plus';



const route = useRoute()
const data = reactive({
    items: {items:[]},
    clusterList: [],
    clusterId: "",
    editItem: {},
    editName: "",
    detailItem: {},
    detailName: "",
    createName: "",
    deleteName: "",
    deleteNameConfirm: ""
})

const loading = ref(true)

const editDialog = ref(false)
const detailDialog = ref(false)
const createNamespaceDialog = ref(false)
const deleteNamespaceDialog = ref(false)

// 展示数据的方法
const detail = (row) => {
    data.detailItem = row
    data.detailName = row.metadata.name
    detailDialog.value = true
}

// 编辑
const edit = (row) => {
    loading.value = true
    data.editItem = row
    data.editName = row.metadata.name
    editDialog.value = true
    loading.value = false
}

const deleteNamespace = (row) => {
    data.deleteName = row.metadata.name
    deleteNamespaceDialog.value = true
}

// 异步转成同步
const getClusterList = async() => {
    await getClusterListHandler().then(
        (res) => {
            data.clusterList = res.data.data.items
        }
    )
}   


// 获取列表
const getList= (clusterId) =>{
    loading.value=true
    getListHandler(clusterId).then((response)=>{
        console.log("response:", response.data.data.items)
        data.items=response.data.data.items
        loading.value=false
    })
}


const filterTableData = computed(() =>
// console.log('data.items:', data.items);
// console.log('typeof data.items:', typeof data.items);
  data.items.items.filter(
    (item) =>
      !search.value ||
      item.metadata.name.toLowerCase().includes(search.value.toLowerCase()) 
  )
)

  


const createNamespace = () => {
    createNamespaceDialog.value = true
}

const submitCreateNamespace = ()=> {
    // 调用创建namespace的接口
    createItem(data.clusterId, data.createName).then((response)=>{
        ElMessage({
            message: response.data.message,
            type: 'success',
        })
        getList(data.clusterId)
        createNamespaceDialog.value = false
    })
}

const submitDeleteNamespace = ()=> {
    if (data.deleteName != data.deleteNameConfirm) {
        return 
    }
    // 调用delete namespace的接口
    deleteItem(data.clusterId, data.deleteName).then((response)=>{
        console.log("respones123:", response)
        ElMessage({
            message: response.data.message,
            type: 'success',
        })
        getList(data.clusterId)
        deleteNamespaceDialog.value = false
        data.deleteNameConfirm = ""
    })
}

onBeforeMount(async()=>{
    // 查询列表之前，要知道哪个集群的节点列表
    // 1、查询到集群列表
    // 2、如果没有指定集群，则给一个默认值，进行获取集群列表
    // 3、如果指定了集群，就直接查询当前集群的节点列表
    // 4、切换了集群之后，应该重新获取集群列表
    // 5、集群不可用，则不可选
    await getClusterList()
    const defaultClusterSelected = data.clusterList[0].id
    // 获取当前请求是否携带了集群ID的参数
    const curClusterId = route.query.clusterId
    data.clusterId = curClusterId?curClusterId:defaultClusterSelected

    getList(data.clusterId) 
})

  

const closeDialog = () => {
    getList(data.clusterId)
}
const rollback = ()=>{
    editDialog.value = false
    getList()
}

const search = ref('')
const { clusterId, clusterList, editItem, editName, detailItem, detailName, createName, deleteName, deleteNameConfirm } = toRefs(data)

</script>

<template>
    <el-card
    class="box-card">
        <template #header>
            <div class="card-header">
            <div>
                <span>命名空间列表</span>
            </div>
            <div class="card-header">
                <el-select v-model="clusterId" placeholder="选择集群" @change="getList(clusterId)">
                    <el-option v-for="item in clusterList"
                    :key="item.id"
                    :label="item.id"
                    :value="item.id"
                    :disabled="item.status == 'InActive'"
                    />
                </el-select>
                <el-input v-model="search" size="small" placeholder="搜索" style="width: 200px;margin-left:20px;height:32px;"  />
                <el-button type="primary" style="margin-left:20px;" @click="createNamespace">创建</el-button>
            </div>
            </div>
        </template>
        <el-table 
            border 
            height="480" 
            v-if="data.items"
            :data="filterTableData" 
            style="width: 100%">
            <el-table-column  fixed prop="" align="center" label="名称">
                <template #default="scope">
                    <el-button link type="primary" @click="detail(scope.row)">{{ scope.row.metadata.name }}</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="metadata.creationTimestamp" align="center" label="创建时间" width="180" />
            <el-table-column prop="" align="center" label="状态" width="80" sortable>
                <template #default="scope">
                    <span v-if="scope.row.status.phase == 'Active'" style="color: green;">Active</span>
                    <span v-else style="color: red;">{{ scope.row.status.phase }}</span>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="180">
                <template #default="scope">
                    <el-button  link type="primary"  @click="edit(scope.row)">复制</el-button>
                    <el-button  link type="primary"  @click="edit(scope.row)">编辑</el-button>
                    <el-button  link type="warning"  @click="deleteNamespace(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>


    </el-card>
    <el-dialog 
    destroy-on-close 
    @close="closeDialog" 
    v-model="editDialog" 
    :title="'正在编辑集群:' + clusterId +'  节点:' + editName"
    width="50%">
        <Edit @rollback="getList" :cluster-id="data.clusterId" :item-form="editItem"></Edit>
    </el-dialog>
    <el-dialog 
    destroy-on-close 
    v-model="detailDialog" 
    :title="'集群:' + clusterId +'  节点:' + detailName"
    width="50%">
        <Detail :item="detailItem"></Detail>
    </el-dialog>

    <el-dialog 
    destroy-on-close 
    v-model="createNamespaceDialog" 
    title="创建命名空间"
    width="40%">
        <el-input v-model.trim="createName" placeholder="请输入namespace名称"></el-input>
        <el-button style="margin-top:20px;" type="primary"  @click="submitCreateNamespace">创建</el-button>
    </el-dialog>

    <el-dialog 
    destroy-on-close 
    v-model="deleteNamespaceDialog" 
    :title="'删除命名空间:' + deleteName"
    width="40%">
        <el-input v-model.trim="deleteNameConfirm" placeholder="请确认删除的名称"></el-input>
        <el-button style="margin-top:20px;" type="warning"  @click="submitDeleteNamespace">删除</el-button>
    </el-dialog>

    <el-dialog 
    destroy-on-close 
    @close="closeDialog" 
    v-model="editDialog" 
    :title="'正在编辑集群:' + clusterId +'  节点:' + editName"
    width="50%">
        <Edit @rollback="getList" :cluster-id="data.clusterId" :item-form="editItem"></Edit>
    </el-dialog>
</template>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.text {
    font-size: 14px;
}
.item {
    margin-bottom: 18px;
}
</style>